package com.ibeeking.found.file.rest.controller.v1;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.file.rest.service.IShareFileService;
import com.ibeeking.found.file.rest.service.IShareService;
import com.ibeeking.found.file.rest.service.IUserFileService;
import com.ibeeking.found.file.rest.service.component.FileDealComp;
import com.ibeeking.found.file.rest.service.util.QiwenFile;
import com.ibeeking.found.file.service.common.dos.ShareDO;
import com.ibeeking.found.file.service.common.dos.ShareFileDO;
import com.ibeeking.found.file.service.common.dos.UserFileDO;
import com.ibeeking.found.file.service.common.param.*;
import com.ibeeking.found.file.service.common.vo.ShareFileListVO;
import com.ibeeking.found.file.service.common.vo.ShareFileVO;
import com.ibeeking.found.file.service.common.vo.ShareListVO;
import com.ibeeking.found.file.service.common.vo.ShareTypeVO;
import com.ibeeking.nematos.constants.enums.OperateLogTypeEnum;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
 * @ClassName ShareController
 * @Description 该接口为文件分享接口
 * @Author ibeeking
 * @Date 2021-06-02 18:15
 **/
@RestController
@Slf4j
@RequestMapping("/share/v1")
public class ShareController {

    public static final String CURRENT_MODULE = "文件分享";

    @Resource
    private IShareFileService shareFileServiceImpl;

    @Resource
    private IShareService shareServiceImpl;

    @Resource
    private IUserFileService userFileServiceImpl;

    @Resource
    private FileDealComp fileDealComp;


    @Log(logType = OperateLogTypeEnum.QUERY, describe = "分享文件")
    @PostMapping(value = "/sharefile")
    public ShareFileVO shareFile( @RequestBody ShareFileParam shareFileDTO) {
        ShareFileVO shareSecretVO = new ShareFileVO();
        Long userId = UserUtils.getUserId();

        String uuid = UUID.randomUUID().toString().replace("-", "");
        ShareDO share = new ShareDO();
        share.setShareId(IdUtil.getSnowflakeNextId());
        BeanUtil.copyProperties(shareFileDTO, share);
        share.setShareTime(LocalDateTime.now());
        share.setUserId(userId);
        share.setShareStatus(0);
        if (shareFileDTO.getShareType() == 1) {
            String extractionCode = RandomUtil.randomNumbers(6);
            share.setExtractionCode(extractionCode);
            shareSecretVO.setExtractionCode(share.getExtractionCode());
        }

        share.setShareBatchNum(uuid);
        shareServiceImpl.save(share);

        List<ShareFileDO> saveFileList = new ArrayList<>();
        String userFileIds = shareFileDTO.getUserFileIds();
        String[] userFileIdList = userFileIds.split(",");
        for (String userFileId : userFileIdList) {
            UserFileDO userFile = userFileServiceImpl.getById(Long.valueOf(userFileId));
            if (userFile.getUserId().compareTo(userId) != 0) {
                throw new BusinessException("您只能分享自己的文件");
            }
            if (userFile.getIsDir() == 1) {
                QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                List<UserFileDO> userfileList = userFileServiceImpl.selectUserFileByLikeRightFilePath(qiwenFile.getPath(), userId);
                for (UserFileDO userFile1 : userfileList) {
                    ShareFileDO shareFile1 = new ShareFileDO();
                    shareFile1.setShareFileId(IdUtil.getSnowflakeNextId());
                    shareFile1.setUserFileId(userFile1.getUserFileId());
                    shareFile1.setShareBatchNum(uuid);
                    shareFile1.setShareFilePath(userFile1.getFilePath().replaceFirst(userFile.getFilePath().equals("/") ? "" : userFile.getFilePath(), ""));
                    saveFileList.add(shareFile1);
                }
            }
            ShareFileDO shareFile = new ShareFileDO();
            shareFile.setShareFileId(IdUtil.getSnowflakeNextId());
            shareFile.setUserFileId(Long.valueOf(userFileId));
            shareFile.setShareFilePath("/");
            shareFile.setShareBatchNum(uuid);
            saveFileList.add(shareFile);


        }
        shareFileServiceImpl.saveBatch(saveFileList);
        shareSecretVO.setShareBatchNum(uuid);

        return shareSecretVO;
    }


    @Log(logType = OperateLogTypeEnum.SAVE, describe = "保存分享文件")
    @PostMapping(value = "/savesharefile")
    @Transactional(rollbackFor=Exception.class)
    public Boolean saveShareFile(@RequestBody SaveShareFileParam saveShareFileDTO) {

//        List<ShareFile> fileList = JSON.parseArray(saveShareFileDTO.getFiles(), ShareFile.class);
        String savefilePath = saveShareFileDTO.getFilePath();
        Long userId = UserUtils.getUserId();
        String[] userFileIdArr = saveShareFileDTO.getUserFileIds().split(",");
        List<UserFileDO> saveUserFileList = new ArrayList<>();
        for (String userFileId : userFileIdArr) {


            UserFileDO userFile = userFileServiceImpl.getById(userFileId);
            String fileName = userFile.getFileName();
            String filePath = userFile.getFilePath();

            UserFileDO userFile2 = new UserFileDO();
            BeanUtil.copyProperties(userFile, userFile2);

            String savefileName = fileDealComp.getRepeatFileName(userFile, savefilePath);

            if (userFile.getIsDir() == 1) {
                ShareFileDO shareFile = shareFileServiceImpl.getOne(new QueryWrapper<ShareFileDO>().lambda().eq(ShareFileDO::getUserFileId, userFileId).eq(ShareFileDO::getShareBatchNum, saveShareFileDTO.getShareBatchNum()));
                List<ShareFileDO> shareFileList = shareFileServiceImpl.list(new QueryWrapper<ShareFileDO>().lambda().eq(ShareFileDO::getShareBatchNum, saveShareFileDTO.getShareBatchNum()).likeRight(ShareFileDO::getShareFilePath, QiwenFile.formatPath(shareFile.getShareFilePath() +"/"+ fileName)));



                for (ShareFileDO shareFile1 : shareFileList) {
                    UserFileDO userFile1 = userFileServiceImpl.getById(shareFile1.getUserFileId());
                    userFile1.setUserFileId(IdUtil.getSnowflakeNextId());
                    userFile1.setUserId(userId);
                    userFile1.setFilePath(userFile1.getFilePath().replaceFirst(QiwenFile.formatPath(filePath + "/" + fileName), QiwenFile.formatPath(savefilePath + "/" + savefileName)));
                    saveUserFileList.add(userFile1);
                    log.info("当前文件：" + JSON.toJSONString(userFile1));
                }
            }
            userFile2.setUserFileId(IdUtil.getSnowflakeNextId());
            userFile2.setUserId(userId);
            userFile2.setFilePath(savefilePath);
            userFile2.setFileName(savefileName);
            saveUserFileList.add(userFile2);

        }
        log.info("----------" + JSON.toJSONString(saveUserFileList));
        userFileServiceImpl.saveBatch(saveUserFileList);

        return true;
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "查看已分享列表")
    @GetMapping(value = "/shareList")
    public List<ShareListVO> shareList(ShareListParam shareListDTO) {
        String userId = UserUtils.getStringUserId();
        List<ShareListVO> shareList = shareServiceImpl.selectShareList(shareListDTO, userId);

        int total = shareServiceImpl.selectShareListTotalCount(shareListDTO, userId);

        return shareList;
    }


    @Log(logType = OperateLogTypeEnum.QUERY, describe = "分享文件列表")
    @GetMapping(value = "/sharefileList")
    public List<ShareFileListVO> shareFileList(ShareFileListDTO shareFileListBySecretDTO) {
        String shareBatchNum = shareFileListBySecretDTO.getShareBatchNum();
        String shareFilePath = shareFileListBySecretDTO.getShareFilePath();
        List<ShareFileListVO> list = shareFileServiceImpl.selectShareFileList(shareBatchNum, shareFilePath);
        for (ShareFileListVO shareFileListVO : list) {
            shareFileListVO.setShareFilePath(shareFilePath);
        }
        return list;
    }


    @Log(logType = OperateLogTypeEnum.QUERY, describe = "分享类型")
    @GetMapping(value = "/sharetype")
    public ShareTypeVO shareType(ShareTypeParam shareTypeDTO) {
        LambdaQueryWrapper<ShareDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShareDO::getShareBatchNum, shareTypeDTO.getShareBatchNum());
        ShareDO share = shareServiceImpl.getOne(lambdaQueryWrapper);
        ShareTypeVO shareTypeVO = new ShareTypeVO();
        shareTypeVO.setShareType(share.getShareType());
        return shareTypeVO;
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "校验提取码")
    @GetMapping(value = "/checkextractioncode")
    public Boolean checkExtractionCode(CheckExtractionCodeParam checkExtractionCodeDTO) {
        LambdaQueryWrapper<ShareDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShareDO::getShareBatchNum, checkExtractionCodeDTO.getShareBatchNum())
                .eq(ShareDO::getExtractionCode, checkExtractionCodeDTO.getExtractionCode());
        List<ShareDO> list = shareServiceImpl.list(lambdaQueryWrapper);
        if (list.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    @Log(logType = OperateLogTypeEnum.QUERY, describe = "校验过期时间")
    @GetMapping(value = "/checkendtime")
    public Boolean checkEndTime(CheckEndTimeParam checkEndTimeDTO) {
        LambdaQueryWrapper<ShareDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShareDO::getShareBatchNum, checkEndTimeDTO.getShareBatchNum());
        ShareDO share = shareServiceImpl.getOne(lambdaQueryWrapper);
        if (share == null) {
            throw new BusinessException("文件不存在！");
        }
        LocalDateTime endTime = share.getEndTime();
        if (endTime.isBefore(LocalDateTime.now()))  {
            throw new BusinessException("分享已过期");
        } else {
            return true;
        }
    }
}
